<template>
	<view class="my-page" :style="containerStyle">
		<!-- 顶部导航栏 -->
		<nav-bar title="我的" :show-back="false">
			<template #right>
				<view class="header-setting" @click="navigateToSetting">
					<text class="setting-icon">⚙️</text>
				</view>
			</template>
		</nav-bar>

		<!-- 加载状态 -->
		<view class="loading-overlay" v-if="isLoading">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 主内容滚动区域 -->
		<scroll-view v-else scroll-y class="content-scroll">
			<!-- 1. 个人资料卡片 -->
			<view class="user-profile-card">
				<!-- 内容区域：左右布局 -->
				<view class="profile-content">
					<!-- 左侧头像区域 -->
					<view class="avatar-section">
						<uni-file-picker limit="1" :del-icon="false" disable-preview="true" :imageStyles="imageStyles"
							v-model="avatar" file-mediatype="image" @select="handleAvatarSelect"></uni-file-picker>
					</view>

					<!-- 右侧用户信息区域 -->
					<view class="user-info-section">
						<view class="user-name-row">
							<text class="user-name">{{ userName }}</text>
							<view class="vip-badge">
								<text class="vip-icon">👑</text>
							</view>
						</view>
						<text class="user-role">{{ userRole }}</text>
						<view class="user-contact">
							<view class="contact-item" v-if="userPhone">
								<text class="contact-icon">📱</text>
								<text class="contact-text">{{ userPhone }}</text>
							</view>
							<view class="contact-item" v-if="userEmail">
								<text class="contact-icon">✉️</text>
								<text class="contact-text">{{ userEmail }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>



			<!-- 2. 系统功能列表 -->
			<view class="system-functions">
				<view class="section-header">
					<text class="section-icon">🔧</text>
					<text class="section-title">系统功能</text>
				</view>
				<view class="function-list">
					<view class="function-item" @click="navigateToAbout">
						<view class="function-left">
							<view class="function-icon" style="background: rgba(139, 92, 246, 0.1);">
								<text>ℹ️</text>
							</view>
							<text class="function-name">关于我们</text>
						</view>
						<view class="function-right">
							<text class="version">v1.0.0</text>
							<text class="arrow">›</text>
						</view>
					</view>
					<view class="function-item" @click="handleLogout">
						<view class="function-left">
							<view class="function-icon" style="background: rgba(239, 68, 68, 0.1);">
								<text>🚪</text>
							</view>
							<text class="function-name logout-text">退出登录</text>
						</view>
						<view class="function-right">
							<text class="arrow">›</text>
						</view>
					</view>
					<view class="function-item" @click="toggleStyleChooser">
						<view class="function-left">
							<view class="function-icon" style="background: rgba(102, 126, 234, 0.1);">
								<text>🎨</text>
							</view>
							<text class="function-name">应用风格</text>
						</view>
						<view class="function-right">
							<text
								class="current-style">{{ styleOptions.find(s => s.value === currentAppStyle)?.name }}</text>
							<text class="arrow" :class="{ rotate: showStyleOptions }">›</text>
						</view>
					</view>
					<view class="style-chooser" v-if="showStyleOptions">
						<view v-for="theme in styleOptions" :key="theme.value"
							:class="['style-option', { active: currentAppStyle === theme.value }]"
							@click="setAppStyle(theme.value)">
							<view class="style-preview" :style="{ background: theme.previewBg }"></view>
							<text class="style-name">{{ theme.name }}</text>
							<text class="check-icon" v-if="currentAppStyle === theme.value">✔</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部间距 -->
			<view class="bottom-spacing"></view>
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed } from "vue";
	import { userInfo, getUserInfos } from '@/stores/user';
	import { baseURL } from '@/utils/config';
	import type { UserTokenInfo } from '@/types/login';
	import { uploadUserAvatar } from "@/services/user";
	import { updateAvatar } from "@/stores/user";
	import { FileType } from "@/types/global";
	import { setTheme, getThemeStyles } from '@/stores/theme';
	import NavBar from '@/components/nav-bar.vue';
	import { showToast } from '@/utils/global';

	/**
	 * 加载状态标志
	 */
	const isLoading = ref(false);

	/**
	 * 用户名称
	 */
	const userName = ref('未登录用户');

	/**
	 * 用户角色
	 */
	const userRole = ref('超市管理员');

	/**
	 * 用户头像
	 */
	const avatar = ref<FileType[]>([]);

	/**
	 * 用户手机号
	 */
	const userPhone = ref('');

	/**
	 * 用户邮箱
	 */
	const userEmail = ref('');

	/**
	 * 是否显示风格选择器
	 */
	const showStyleOptions = ref(false);

	/**
	 * 当前应用风格
	 */
	const currentAppStyle = ref('default');

	/**
	 * 风格选项配置
	 */
	const styleOptions = ref([
		{
			name: '默认风格',
			value: 'default',
			previewBg: 'radial-gradient(circle, rgba(63, 94, 251, 1) 0%, rgba(252, 70, 107, 1) 100%)'
		},
		{
			name: '清新绿',
			value: 'green',
			previewBg: 'linear-gradient(135deg, #4ade80 0%, #22c55e 100%)'
		},
		{
			name: '彩虹风格',
			value: 'orange',
			previewBg: 'linear-gradient(135deg, rgba(131, 58, 180, 1) 0%, rgba(253, 29, 29, 1) 50%, rgba(252, 176, 69, 1) 100%)'
		},
		{
			name: '科技蓝',
			value: 'blue',
			previewBg: 'linear-gradient(90deg, rgba(2, 0, 36, 1) 0%, rgba(9, 9, 121, 1) 35%, rgba(0, 212, 255, 1) 100%)'
		},
		{
			name: '梦幻粉',
			value: 'pink',
			previewBg: 'radial-gradient(circle, rgba(238, 174, 202, 1) 0%, rgba(148, 187, 233, 1) 100%)'
		},
		{
			name: '暗夜黑',
			value: 'dark',
			previewBg: 'linear-gradient(135deg, #22223b 0%, #3a3550 60%, #6366f1 100%)'
		}
	]);

	// 头像样式配置（单位为px，对应CSS中的160rpx）
	const imageStyles = ref({
		width: 160,
		height: 160,
		border: {
			radius: '50%',
			width: 0,
			color: 'transparent'
		}
	})


	/**
	 * 导航到设置页面
	 */
	const navigateToSetting = () => {
		uni.navigateTo({
			url: '/pages/my/setting/index'
		});
	};

	/**
	 * 导航到关于我们页面
	 */
	const navigateToAbout = () => {
		showToast('功能开发中');
	};

	/**
	 * 切换风格选择器显示状态
	 */
	const toggleStyleChooser = () => {
		showStyleOptions.value = !showStyleOptions.value;
	};

	/**
	 * 设置应用风格
	 * @param {string} style 风格值
	 */
	const setAppStyle = (style : string) => {
		currentAppStyle.value = style;

		// 使用主题 store 切换全局主题
		setTheme(style);

		// 显示提示
		showToast('风格已切换');
		// 关闭选择器
		showStyleOptions.value = false;
	};

	/**
	 * 退出登录
	 */
	const handleLogout = () => {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					// TODO: 清除用户信息和 token
					showToast('已退出登录');
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/index'
						});
					}, 1500);
				}
			}
		});
	};
	/**
	 * 更新用户信息
	 * @description 从用户信息存储中获取并更新用户相关信息
	 */
	const handleUserInfoUpdate = () => {
		const userData = userInfo.value as UserTokenInfo;
		userName.value = userData?.userName || '未登录用户';
		// 更新头像URL
		if (userData?.avatar) {
			if (!avatar.value[0]) {
				avatar.value[0] = { url: '', extname: '', name: '' };
			}
			avatar.value[0].url = baseURL + userData.avatar;
		}
		userPhone.value = userData?.phone || '';
		userEmail.value = userData?.email || '';

		// 设置用户角色（可以从用户数据中获取）
		userRole.value = userData?.role || '超市管理员';
	};

	/**
	 * 处理头像选择
	 * @param {any} file 选择的文件信息
	 */
	const handleAvatarSelect = (file) => {
		console.log('选择的头像文件:', file);
		// 检查是否有选择文件
		if (file && file.tempFiles && file.tempFiles.length > 0) {
			// 调用上传函数
			uploadUserAvatar(file.tempFiles[0]).then(response => {
				handleAvatarUploadSuccess(response);
			}).catch(error => {
				handleAvatarUploadFail(error);
			});
		}
	};

	/**
	 * 处理头像上传成功
	 * @param {AvatarUploadResult} response 上传成功的响应信息
	 */
	const handleAvatarUploadSuccess = (response) => {
		console.log('头像上传成功:', response);
		try {
			// 更新头像URL
			if (response && response.url) {
				//更新用户头像
				updateAvatar(response.url)

				// 可以在这里更新用户存储中的头像信息
				showToast('头像上传成功');
			} else {
				throw new Error('响应数据格式不正确');
			}
		} catch (error) {
			console.error('处理上传成功响应失败:', error);
			handleAvatarUploadFail(error);
		}
	};

	/**
	 * 处理头像上传失败
	 * @param {any} error 上传失败的错误信息
	 */
	const handleAvatarUploadFail = (error) => {
		console.error('头像上传失败:', error);

		showToast('头像上传失败，请重试');

	};

	// 获取主题样式
	const themeStyles = computed(() => getThemeStyles());

	// 容器背景样式
	const containerStyle = computed(() => ({
		background: themeStyles.value.bgGradient
	}));

	/**
	 * 页面加载时执行的初始化函数
	 * @description 页面加载时获取用户信息，更新UI状态
	 */
	onMounted(async () => {
		isLoading.value = true;

		try {
			// 获取用户基本信息
			await getUserInfos();
			// 更新用户信息
			handleUserInfoUpdate();
			// 加载保存的应用风格
			const savedStyle = uni.getStorageSync('appStyle');
			if (savedStyle) {
				currentAppStyle.value = savedStyle;
			}

		} catch (error) {
			console.error('加载数据失败:', error);
			showToast('加载数据失败');
		} finally {
			setTimeout(() => {
				isLoading.value = false;
			}, 500);
		}
	});
</script>

<style lang="scss">
	/* 页面容器 */
	.my-page {
		height: 100vh;
		width: 100%;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		/* background 由 containerStyle 动态设置 */
	}

	/* 主内容滚动区域 */
	.content-scroll {
		flex: 1;
		height: 0;
	}

	/* 顶部导航栏右侧设置按钮 */
	.header-setting {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 56rpx;
		height: 56rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.2);
		backdrop-filter: blur(10rpx);
		transition: all 0.3s ease;

		.setting-icon {
			font-size: 36rpx;
		}

		&:active {
			background: rgba(255, 255, 255, 0.3);
			transform: scale(0.95);
		}
	}

	/* 加载状态遮罩 */
	.loading-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0.9);
		backdrop-filter: blur(10rpx);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		z-index: 1000;

		.loading-spinner {
			width: 80rpx;
			height: 80rpx;
			border: 6rpx solid v-bind('themeStyles.primaryColor + "33"');
			border-top-color: v-bind('themeStyles.primaryColor');
			border-radius: 50%;
			animation: spin 1s linear infinite;
		}

		.loading-text {
			margin-top: 24rpx;
			font-size: 28rpx;
			color: v-bind('themeStyles.primaryColor');
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

	/* 1. 个人资料卡片 */
	.user-profile-card {
		margin: 32rpx;
		padding: 40rpx;
		border-radius: 32rpx;
		background: v-bind('themeStyles.bgCard');
		box-shadow: v-bind('themeStyles.cardBoxShadow');
		position: relative;
		overflow: hidden;
		border: 1rpx solid v-bind('themeStyles.borderLight');

		/* 内容区域：左右布局 */
		.profile-content {
			display: flex;
			align-items: center;
			gap: 32rpx;
			position: relative;
			z-index: 1;

		/* 左侧头像区域 */
		.avatar-section {
			flex-shrink: 0;
			width: 160rpx;
			height: 160rpx;
			border-radius: 50%;
			overflow: hidden;
			background: v-bind('themeStyles.bgSecondary');
			box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
			border: 4rpx solid v-bind('themeStyles.primaryColor');
			position: relative;
			transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

			&:active {
				transform: scale(0.98);
			}

			/* 确保uni-file-picker组件所有层级都是圆形并填充满 */
			::v-deep .uni-file-picker {
				width: 100% !important;
				height: 100% !important;
			}

			::v-deep .uni-file-picker__container {
				width: 100% !important;
				height: 100% !important;
				border-radius: 50% !important;
				overflow: hidden !important;
				padding: 0 !important;
				margin: 0 !important;
			}

			::v-deep .file-picker__box {
				width: 100% !important;
				height: 100% !important;
				border-radius: 50% !important;
				overflow: hidden !important;
				padding: 0 !important;
				margin: 0 !important;
			}

			::v-deep .file-picker__item {
				width: 100% !important;
				height: 100% !important;
				border-radius: 50% !important;
				overflow: hidden !important;
				padding: 0 !important;
				margin: 0 !important;
			}

			::v-deep .file-image {
				width: 100% !important;
				height: 100% !important;
				border-radius: 50% !important;
				object-fit: cover !important;
			}

			::v-deep image {
				width: 100% !important;
				height: 100% !important;
				border-radius: 50% !important;
				object-fit: cover !important;
				display: block !important;
			}

			::v-deep .is-add {
				width: 100% !important;
				height: 100% !important;
				border-radius: 50% !important;
				display: flex !important;
				align-items: center !important;
				justify-content: center !important;
			}
		}

			/* 右侧用户信息区域 */
			.user-info-section {
				flex: 1;
				min-width: 0; /* 防止文本溢出 */
				display: flex;
				flex-direction: column;
				gap: 16rpx;

				/* 用户名和VIP徽章行 */
				.user-name-row {
					display: flex;
					align-items: center;
					gap: 12rpx;

					.user-name {
						font-size: 36rpx;
						font-weight: 700;
						color: v-bind('themeStyles.textPrimary');
						letter-spacing: 0.5rpx;
						flex-shrink: 1;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					.vip-badge {
						flex-shrink: 0;
						padding: 6rpx 12rpx;
						background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
						border-radius: 8rpx;
						box-shadow: 0 2rpx 8rpx rgba(251, 191, 36, 0.3);

						.vip-icon {
							font-size: 24rpx;
							display: block;
							line-height: 1;
						}
					}
				}

				/* 用户角色标签 */
				.user-role {
					font-size: 24rpx;
					color: v-bind('themeStyles.textSecondary');
					font-weight: 600;
					padding: 6rpx 16rpx;
					background: v-bind('themeStyles.accentBg');
					border-radius: 12rpx;
					display: inline-block;
					border: 1rpx solid v-bind('themeStyles.accentBorder');
					align-self: flex-start;
				}

				/* 联系方式列表 */
				.user-contact {
					display: flex;
					flex-direction: column;
					gap: 10rpx;

					.contact-item {
						display: flex;
						align-items: center;
						gap: 8rpx;
						font-size: 24rpx;

						.contact-icon {
							font-size: 28rpx;
							flex-shrink: 0;
						}

						.contact-text {
							color: v-bind('themeStyles.textTertiary');
							font-weight: 500;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}
					}
				}
			}
		}
	}

	/* 2. 系统功能列表 */
	.system-functions {
		margin: 0 32rpx 32rpx;
		padding: 32rpx;
		border-radius: 32rpx;
		background: v-bind('themeStyles.bgCard');
		box-shadow: v-bind('themeStyles.cardBoxShadow');
		border: 1px solid v-bind('themeStyles.borderLight');

		.function-list {
			margin-top: 24rpx;
			display: flex;
			flex-direction: column;
			gap: 0;

			.function-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 28rpx 0;
				border-bottom: 1rpx solid v-bind('themeStyles.borderLight');
				transition: all 0.3s ease;

				&:last-child {
					border-bottom: none;
				}

				&:active {
					background: v-bind('themeStyles.bgSecondary');
					opacity: 0.9;
				}

				.function-left {
					display: flex;
					align-items: center;
					gap: 24rpx;

					.function-icon {
						width: 72rpx;
						height: 72rpx;
						border-radius: 16rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 32rpx;
					}

					.function-name {
						font-size: 28rpx;
						color: v-bind('themeStyles.textPrimary');
						font-weight: 500;

						&.logout-text {
							color: v-bind('themeStyles.errorColor');
						}
					}
				}

				.function-right {
					display: flex;
					align-items: center;
					gap: 16rpx;

					.badge {
						padding: 4rpx 12rpx;
						background: #ef4444;
						color: white;
						font-size: 20rpx;
						font-weight: 600;
						border-radius: 12rpx;
						min-width: 32rpx;
						text-align: center;
					}

					.version {
						font-size: 24rpx;
						color: v-bind('themeStyles.textTertiary');
					}

					.current-style {
						font-size: 24rpx;
						color: v-bind('themeStyles.primaryColor');
						font-weight: 600;
					}

					.arrow {
						font-size: 40rpx;
						color: v-bind('themeStyles.textTertiary');
						font-weight: 300;
						transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);

						&.rotate {
							transform: rotate(90deg);
						}
					}
				}
			}
		}

		/* 风格选择器 */
		.style-chooser {
			margin-top: 16rpx;
			padding: 24rpx;
			background: v-bind('themeStyles.bgSecondary');
			border-radius: 20rpx;
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx 16rpx;
			animation: slideDown 0.3s cubic-bezier(0.4, 0, 0.2, 1);

			.style-option {
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 12rpx;
				padding: 20rpx;
				background: v-bind('themeStyles.bgCard');
				border-radius: 16rpx;
				border: 2rpx solid v-bind('themeStyles.borderLight');
				transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
				position: relative;

				&.active {
					border-color: v-bind('themeStyles.primaryColor');
					box-shadow: v-bind('themeStyles.activeShadow');
					transform: scale(1.02);
				}

				&:active {
					transform: scale(0.98);
				}

				.style-preview {
					width: 100%;
					height: 80rpx;
					border-radius: 12rpx;
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
				}

				.style-name {
					font-size: 24rpx;
					color: v-bind('themeStyles.textSecondary');
					font-weight: 600;
				}

				.check-icon {
					position: absolute;
					top: 8rpx;
					right: 8rpx;
					width: 32rpx;
					height: 32rpx;
					background: v-bind('themeStyles.primaryColor');
					color: white;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 18rpx;
					font-weight: bold;
				}
			}
		}
	}

	/* 动画定义 */
	@keyframes slideDown {
		from {
			opacity: 0;
			transform: translateY(-10rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	/* 通用区块头部样式 */
	.section-header {
		display: flex;
		align-items: center;
		gap: 12rpx;

		.section-icon {
			font-size: 40rpx;
		}

		.section-title {
			flex: 1;
			font-size: 32rpx;
			font-weight: 700;
			color: v-bind('themeStyles.textPrimary');
		}
	}

	/* 底部间距 */
	.bottom-spacing {
		height: 40rpx;
	}
</style>